package service.impl;

import dao.BookDao;
import dao.OrderDao;
import dao.OrderItemDao;
import dao.impl.BookDaoImpl;
import dao.impl.OrderDaoImpl;
import dao.impl.OrderItemDaoImpl;
import pojo.*;
import service.OrderService;

import java.util.List;
import java.util.Map;

/**
 * @author Wxt
 * @create 2022-02-12 13:51
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();
    @Override
    public String createOrder(Cart cart, int userId) {
        String orderId = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderId, new java.sql.Date(new java.util.Date().getTime()), cart.getTotalPrice(), 0, userId);
        orderDao.saveOrder(order);
        for (Map.Entry<Integer, CartItem> cartItemEntry : cart.getItems().entrySet()) {
            CartItem cartItem = cartItemEntry.getValue();
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId);
            orderItemDao.saveOrderItem(orderItem);
            Book book = bookDao.queryForOneById(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            bookDao.updateBook(book);
        }
        cart.clear();
        return orderId;
    }

    @Override
    public List<Order> showAllOrders() {
        return orderDao.queryOrders();
    }

    @Override
    public void sendOrder(String orderId) {
        orderDao.changeOrderStatus(orderId, 1);
    }

    @Override
    public List<OrderItem> showOrderDetail(String orderId) {
        return orderItemDao.queryOrderItemsByOrderId(orderId);
    }

    @Override
    public List<Order> showMyOrders(int userId) {
        return orderDao.queryOrdersByUserId(userId);
    }

    @Override
    public void receiverOrder(String orderId) {
        orderDao.changeOrderStatus(orderId, 2);
    }

    @Override
    public Page<Order> page(int pageNo, int pageSize) {
        Page<Order> page = new Page<>();
        page.setPageSize(Page.PAGE_SIZE);
        int totalCount = orderDao.queryForPageTotalCount();
        page.setPageCount(totalCount);
        int pageTotal = page.getPageCount() / pageSize;
        if(page.getPageCount() % pageSize != 0) {
            pageTotal = pageTotal + 1;
        }
        page.setPageTotal(pageTotal);
        if(pageNo < 1) {
            pageNo = 1;
        }
        if(pageNo > page.getPageTotal()) {
            pageNo = page.getPageTotal();
        }
        page.setPageNo(pageNo);
        int begin = (page.getPageNo() - 1) * pageSize;
        List<Order> orders = orderDao.queryForOrders(begin, pageSize);
        page.setPageItems(orders);
        return page;
    }
}
